package me.keiwu.user.controller.pub;

import com.alibaba.fastjson.JSONObject;
import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.data.wx.WXStepData;
import me.keiwu.pub.data.wx.WXStepInfo;
import me.keiwu.pub.data.wx.WXUserInfoData;
import me.keiwu.pub.service.WXService;
import me.keiwu.pub.util.DateUtil;
import me.keiwu.pub.util.DebugUtil;
import me.keiwu.user.service.RobotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by kei on 11/01/2018.
 */
@RestController
@RequestMapping("/pub/robot")
public class RobotPubController {

    @Autowired
    private RobotService robotService;
    @Autowired
    private WXService wxService;
    @Autowired
    private DebugUtil debugUtil;


    @RequestMapping("/loginAndCommit")
    public ResponseV2 loginAndCommit(String loginData, String stepData, Integer step) {
        if (!debugUtil.isPressureTest()) return ResponseV2.fail(404, "interface not open");

        String code = "testCode";
        String sessionKey = "CWvwAQAvrIlqrG42eHSsBQ==";
        String iv = "CWvwAQAvrIlqrG42eHSsBQ==";

        wxService.getSession(code);
        wxService.decryptData(loginData, iv, sessionKey, WXUserInfoData.class);

        ResponseV2 loginResp = robotService.login();
        JSONObject data = (JSONObject) loginResp.getData();
        long userId = data.getLong("userId");
        String token = data.getString("accessToken");

        wxService.decryptData(stepData, iv, sessionKey, WXStepData.class);

        WXStepData robotData = new WXStepData();
        List<WXStepInfo> list = new ArrayList<>();
        Date now = new Date();
        for (int i = 0; i < 30; i++) {
            WXStepInfo info = new WXStepInfo();
            info.setStep(step);
            info.setTimestamp(DateUtil.getUnixTime(DateUtil.addDays(now, -i)));
            list.add(info);
        }
        robotData.setStepInfoList(list);
        ResponseV2 stepResp = robotService.commitStep(userId, robotData);

        robotService.commitLbs(userId);

        JSONObject res = (JSONObject) stepResp.getData();
        res.put("accessToken", token);
        res.put("userId", userId);
        return ResponseV2.ok(res);
    }

}
